#include "Precomp.h"
#include "Utils.h"

std::string toUTF8(const wchar_t* str)
{
	std::string ret;
	size_t len=wcslen(str);
	ret.reserve(len*sizeof(wchar_t)+1);
	switch(sizeof(wchar_t))
	{
	case 2:
		sf::Unicode::UTF16ToUTF8(str,&str[len],std::back_inserter(ret));
	break;
	case 4:
		sf::Unicode::UTF32ToUTF8(str,&str[len],std::back_inserter(ret));
	break;
	}
	return ret;
}

std::wstring toWCS(const char* str)
{
	std::wstring ret;
	size_t rawlen=strlen(str);
	ret.reserve(sf::Unicode::GetUTF8Length(str,&str[rawlen])+1);
	switch(sizeof(wchar_t))
	{
	case 2:
		sf::Unicode::UTF8ToUTF16(str,&str[rawlen],std::back_inserter(ret));
	break;
	case 4:
		sf::Unicode::UTF8ToUTF32(str,&str[rawlen],std::back_inserter(ret));
	break;
	}
	return ret;
}

bool isPointInBox(const sf::Vector2f& size, const sf::Matrix3& transform, const sf::Vector2f& point)
{
	sf::Vector2f pos=transform.GetInverse().Transform(point);//transform the point to the matrix's coordinate
	if((pos.x>=0)&&(pos.x<=size.x)&&(pos.y>=0)&&(pos.y<=size.y))
		return true;
	else
		return false;
}

bool checkBoxCollision(const sf::Vector2f& size,const sf::Matrix3& transform, const sf::Vector2f& size2,const sf::Matrix3& transform2)
{
	sf::Matrix3 itransform=transform.GetInverse();
	sf::Matrix3 itransform2=transform2.GetInverse();
	sf::Vector2f p1,p2,p3,p4;
	//check 1 against 2
	p1=itransform2.Transform(transform.Transform(sf::Vector2f(0,0)));
	p2=itransform2.Transform(transform.Transform(sf::Vector2f(size.x,0)));
	p3=itransform2.Transform(transform.Transform(sf::Vector2f(size.x,size.y)));
	p4=itransform2.Transform(transform.Transform(sf::Vector2f(0,size.y)));
	if(isPointInBox(size2,transform2,p1))
		return true;
	if(isPointInBox(size2,transform2,p2))
		return true;
	if(isPointInBox(size2,transform2,p3))
		return true;
	if(isPointInBox(size2,transform2,p4))
		return true;
	//check 2 against 1
	p1=itransform.Transform(transform2.Transform(sf::Vector2f(0,0)));
	p2=itransform.Transform(transform2.Transform(sf::Vector2f(size2.x,0)));
	p3=itransform.Transform(transform2.Transform(sf::Vector2f(size2.x,size2.y)));
	p4=itransform.Transform(transform2.Transform(sf::Vector2f(0,size2.y)));
	if(isPointInBox(size,transform,p1))
		return true;
	if(isPointInBox(size,transform,p2))
		return true;
	if(isPointInBox(size,transform,p3))
		return true;
	if(isPointInBox(size,transform,p4))
		return true;
	return false;
}